package com.wwwarehouse.carddesk.fragment.teamfragment.watcherfragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.wwwarehouse.carddesk.R;
import com.wwwarehouse.carddesk.bean.CardDeskGroupGetGroupBean;
import com.wwwarehouse.carddesk.bean.GroupHtmlDataBean;
import com.wwwarehouse.carddesk.constant.CardDeskConstant;
import com.wwwarehouse.carddesk.fragment.teamfragment.checkdownclassfragemnt.DelayTaskFragment;
import com.wwwarehouse.carddesk.fragment.teamfragment.checkdownclassfragemnt.DownClassFragment;
import com.wwwarehouse.carddesk.fragment.teamfragment.commenttargetweb.AgeingTargetFragmnent;
import com.wwwarehouse.carddesk.fragment.teamfragment.commenttargetweb.EfficiencyTargetFragmnent;
import com.wwwarehouse.carddesk.fragment.teamfragment.commenttargetweb.QualityTargetFragmnent;
import com.wwwarehouse.common.activity.base.BaseApplication;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.CircleImageView;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.custom_widget.button.StateButton;
import com.wwwarehouse.common.custom_widget.popupwindow.EasyPopupWindow;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.common.tools.ToastUtils;

/**
 * @创建者 chenchao.
 * @创建时间 2017/11/8 19:27
 * @描述 ${TODO}
 * 上啦延时 上啦下属
 */

public class WatcherLookCreaterFragment extends BaseFragment implements View.OnClickListener {

    private View mView;
    private ElasticScrollView mElasticScrollView;
    private CircleImageView mCivHead;
    private TextView mTvName;
    private TextView mTvRole;
    private TextView mTvCompanyName;
    private LinearLayout mLlDetail;
    private BridgeWebView mBwWebView;
    private StateButton mBtConnect;
    private StateButton mBtBackTeam;
    private StateButton mBtUnder;
    private boolean isShow;
    private EasyPopupWindow   mEasyPopupWindow;
    private View              PopItemView;
    private ImageView mIvAsk;
    private RelativeLayout mRlElse;
    private RelativeLayout.LayoutParams  mParams;
    private TextView mTvTeamName;
    private LinearLayout mLlHaveData;
    private LinearLayout mLlNoData;
    private StateButton mBtDelay;
    private CardDeskGroupGetGroupBean.ListBean mBean;
    private Bundle mToDelayBundle;
    private DelayTaskFragment mDelayTaskFragment;
    private Bundle mToDownClassBundle;
    private DownClassFragment mDownClassFragment;
    private StateLayout mStateLayout;
    private String mNewUrl;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_watcher_look_creater, container, false);
        initView();
        return mView;
    }

    private void initView() {
        mElasticScrollView = findView(mView, R.id.esv_elastic);
        mStateLayout = findView(mView, R.id.sl_layout);
        mRlElse = findView(mView, R.id.rl_else);
        mParams = (RelativeLayout.LayoutParams) mRlElse.getLayoutParams();
        mCivHead = findView(mView, R.id.civ_head);
        mTvName = findView(mView, R.id.tv_name);
        mTvRole = findView(mView, R.id.tv_role);
        mTvCompanyName = findView(mView, R.id.tv_company_name);
        mTvTeamName = findView(mView, R.id.tv_team_name);
        mLlDetail = findView(mView, R.id.ll_detail);
        mIvAsk = findView(mView, R.id.iv_ask);
        mBwWebView = findView(mView, R.id.bw_web_view);
        mLlHaveData = findView(mView, R.id.ll_have_data);
        mLlNoData = findView(mView, R.id.ll_no_data);
        mBtConnect = findView(mView, R.id.bt_connect);
        mBtBackTeam = findView(mView, R.id.bt_back_team);
        mBtDelay = findView(mView, R.id.bt_delay);
        mBtUnder = findView(mView, R.id.bt_under);

        mLlDetail.setOnClickListener(this);
        mBtConnect.setOnClickListener(this);
        mBtBackTeam.setOnClickListener(this);
        mBtUnder.setOnClickListener(this);
        mBtDelay.setOnClickListener(this);
        mElasticScrollView.setOnPullListener(new ElasticScrollView.OnPullListener() {
            @Override
            public void onDownPull() {

            }

            @Override
            public void onUpPull() {
                if (!isShow) {
                    mBtUnder.setVisibility(View.VISIBLE);
                    if (1 == mBean.getIsDelayed()) {
                        mBtDelay.setVisibility(View.VISIBLE);
                    }
                    mParams.setMargins(ConvertUtils.dip2px(mActivity, 11), ConvertUtils.dip2px(mActivity, 5), ConvertUtils.dip2px(mActivity, 11), ConvertUtils.dip2px(mActivity, 59));
                    mRlElse.setLayoutParams(mParams);
                } else {
                    mBtUnder.setVisibility(View.INVISIBLE);
                    mBtDelay.setVisibility(View.INVISIBLE);
                    mParams.setMargins(ConvertUtils.dip2px(mActivity, 11), ConvertUtils.dip2px(mActivity, 5), ConvertUtils.dip2px(mActivity, 11), ConvertUtils.dip2px(mActivity, 36));
                    mRlElse.setLayoutParams(mParams);
                }
                isShow = !isShow;
            }
        });

        String env = sp.getValue(Constant.sp_Env, sp.getValue(Constant.sp_EnvDefault, Constant.ENV_DEFAULT));
        if (Constant.ENV_DEV.equals(env)) {
            mBaseUrl = Constant.URL_WEB_BASE_DEV;
        } else if (Constant.ENV_CIT.equals(env)) {
            mBaseUrl = Constant.URL_WEB_BASE_CIT;
        } else if (Constant.ENV_SIT.equals(env)) {
            mBaseUrl = "";
        } else if (Constant.ENV_UAT.equals(env)) {
            mBaseUrl = Constant.URL_WEB_BASE_UAT;
        } else if (Constant.ENV_RELEASE.equals(env)) {
            mBaseUrl = Constant.URL_WEB_BASE_RELEASE;
        } else if (Constant.ENV_CIT2.equals(env)) {
            mBaseUrl = Constant.URL_WEB_BASE_CIT2;
        }
        mNewUrl = mBaseUrl + CardDeskConstant.PATH_GROUP_PARTR_H5_URL;
        bundleBean = getArguments().getParcelable("bean");
        mBwWebView.loadUrl(mNewUrl);
        mStateLayout.showProgressView(true);
        mBwWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if(newProgress == 100){
                    mStateLayout.showContentView();
                }else{
                }
            }
        });
        registJsMethod();
    }

    private String mBaseUrl = "";
    private CardDeskGroupGetGroupBean.ListBean bundleBean;
    private String data;

    private void registJsMethod() {

        GroupHtmlDataBean bean = new GroupHtmlDataBean();
        bean.setToken(BaseApplication.sp.getValue(Constant.sp_Token));
        if(bundleBean != null ){
            bean.setRankingCompany(new String[]{bundleBean.getBuId()});
            bean.setRankingUser(new String[]{bundleBean.getUserId()});
            bean.setIsTriMember(1);
            bean.setPrivilegeUp(new String[]{});
            bean.setPrivilegeDown(new String[]{});
        }


//        bean.setRankingCompany(new String[]{"10"});
//        bean.setRankingUser(new String[]{"1"});
//        bean.setIsTriMember(1);
//        bean.setPrivilegeUp("");
//        bean.setPrivilegeDown("");

        data = JSON.toJSON(bean).toString();

        //Js获取请求的参数
        mBwWebView.callHandler("getData", data, new CallBackFunction() {
            @Override
            public void onCallBack(String responseData) {
                ToastUtils.showToast(responseData);
            }
        });

        //隐藏StateLayout和ProgressDialog
        mBwWebView.registerHandler("hideProgress", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //                dismissProgressDialog();
                mStateLayout.showContentView();
            }
        });

        //显示progressDialog
        mBwWebView.registerHandler("showProgress", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //                showProgressDialog("正在加载...");
                mStateLayout.showProgressView(true);
            }
        });

        //显示错误信息
        mBwWebView.registerHandler("showErrorMsg", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //                dismissProgressDialog();
                //                toast("" + data);
                mStateLayout.showSystemView(true);
                mStateLayout.setSystemListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mBwWebView.loadUrl(mNewUrl);
                        //        mBwWebView.loadUrl("http://192.168.72.177:8888/app/teamFrame/teamMember.html");
                        mStateLayout.showProgressView(true);
                    }
                });
            }
        });

        //显示没有数据view
        mBwWebView.registerHandler("showNotData", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                mLlHaveData.setVisibility(View.GONE);
                //                dismissProgressDialog();
                mStateLayout.showContentView();
                mLlNoData.setVisibility(View.VISIBLE);
            }
        });

        //点击时效
        mBwWebView.registerHandler("gotoAging", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Bundle bundle = new Bundle();
                bundle.putInt("IsTriMember", 1);
                bundle.putParcelable("bean",bundleBean);
                AgeingTargetFragmnent fragment = new AgeingTargetFragmnent();
                fragment.setArguments(bundle);
                pushFragment(fragment);
            }
        });

        //点击效率
        mBwWebView.registerHandler("gotoEffective", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Bundle bundle = new Bundle();
                bundle.putInt("IsTriMember", 1);
                bundle.putParcelable("bean",bundleBean);
                EfficiencyTargetFragmnent fragmnent = new EfficiencyTargetFragmnent();
                fragmnent.setArguments(bundle);
                pushFragment( fragmnent );
            }
        });

        //点击品质
        mBwWebView.registerHandler("gotoQuality", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Bundle bundle = new Bundle();
                bundle.putInt("IsTriMember", 1);
                bundle.putParcelable("bean",bundleBean);
                QualityTargetFragmnent fragmnent = new QualityTargetFragmnent();
                fragmnent.setArguments(bundle);
                pushFragment(fragmnent);
            }
        });

    }
    
    @Override
    public void setTitle() {
        if (peekFragment() instanceof WatcherLookCreaterFragment) {
            mActivity.setTitle(R.string.teamdesk_member);
        }
    }

    @Override
    public void requestDatas() {
        //延时详情的bundle以及fragment
        mToDelayBundle = new Bundle();
        mDelayTaskFragment = new DelayTaskFragment();

        //下属的bundle以及fragment
        mToDownClassBundle = new Bundle();
        mDownClassFragment = new DownClassFragment();

        if (getArguments() != null && getArguments().getParcelable("bean") != null) {
            Bundle bundle = getArguments();
            mBean = (CardDeskGroupGetGroupBean.ListBean) bundle.getParcelable("bean");
        }
        BaseApplication.getApplicationInstance().displayImg(mBean.getFaceUrl(), mCivHead);
        mTvName.setText(mBean.getPersonName());
        mTvRole.setText(mBean.getCardManagerType());
        mTvCompanyName.setText(String.format("    %s    ", mBean.getBuName()));
        mTvTeamName.setText(String.format(mActivity.getResources().getString(R.string.teamdesk_team), mBean.getPersonName()));
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ll_detail) {
            PopUpUtils.showBubbleUpTeam(mIvAsk, mActivity, String.format(mActivity.getResources().getString(R.string.teamdesk_power_from),mBean.getPersonName(),mBean.getPersonName()), ConvertUtils.dip2px(mActivity, 11), 0);
        } else if (id == R.id.bt_connect) {
            if (mBean.getMobile() != null) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mBean.getMobile()));
                startActivity(intent);
            }
        } else if (id == R.id.bt_back_team) {
            popFragment();
        } else if(id==R.id.bt_delay){
            mToDelayBundle.putString("userId", mBean.getUserId());
            mDelayTaskFragment.setArguments(mToDelayBundle);
            pushFragment(mDelayTaskFragment);
        }else if (id == R.id.bt_under) {
            mToDownClassBundle.putString("userId", mBean.getUserId());
            mToDownClassBundle.putString("leadFaceUrl",mBean.getFaceUrl());
            mToDownClassBundle.putString("leadName",mBean.getPersonName());
            mDownClassFragment.setArguments(mToDownClassBundle);
            pushFragment(mDownClassFragment);
        }
    }

}
